<template>
  <cml-module-item :title="titleText"
    tipName='cache'>
    <button class="cml-base-button title-try"
      @click.stop="setClearCache">
      {{ $t('cmlpanel.clearCacheButton') }}
    </button>
  </cml-module-item>
</template>
<script>
import CmlModuleItem from '../cml-module-item'

export default {
  name: 'Cache',
  components: {
    CmlModuleItem
  },
  model: {},
  props: {},
  data() {
    return {
      isClearCache: false
    }
  },
  computed: {
    titleText() {
      return this.$t('cmlpanel.clearCacheText')
    }
  },
  created() {},
  mounted() {},
  beforeDestroy() {},
  methods: {
    setClearCache(val) {
      this.isClearCache = true
      if (val) {
        localStorage.clear()
        sessionStorage.clear()
        this.clearAllCookie()
        this.clearIndexDB()
      }
    },
    clearAllCookie() {
      var date = new Date()
      date.setTime(date.getTime() - 10000)
      var keys = document.cookie.match(/[^ =;]+(?=\=)/g)
      if (keys) {
        for (var i = keys.length; i--; )
          document.cookie =
            keys[i] + '=0; expire=' + date.toGMTString() + '; path=/'
      }
    },
    clearIndexDB() {
      //打开3d模型常用缓存数据库
      openDB('UnityCache')
      function openDB(name) {
        var request = window.indexedDB.open(name) //建立打开IndexedDB
        request.onerror = function (e) {
          console.log('open indexdb error')
        }

        request.onsuccess = function (e) {
          // myDB.db = e.target.result //这是一个 IDBDatabase对象，这就是IndexedDB对象
          // console.log(myDB.db) //此处就可以获取到db实例

          //若打开成功/没有该数据库名称存在，则删除3d模型生成的indexDB,目前只知道这3个
          window.indexedDB.deleteDatabase('UnityCache')
          window.indexedDB.deleteDatabase('/idbfs-test')
          window.indexedDB.deleteDatabase('/idbfs')
          app.msg({ content: '缓存已清除' })
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.title-try {
  font-size: 12px;
}
</style>
